package com.luoy.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Aspect
@Component
public class WebParamsAspect implements Ordered {
	private static final Logger logger = LoggerFactory.getLogger(WebParamsAspect.class);

	@Pointcut("@annotation(com.luoy.aspect.WebParamsRecord)")
	public void webParamPointcut() {
	}

	/**
	 * 拦截器具体实现
	 * 
	 * @param
	 * @return JsonResult（被拦截方法的执行结果，或需要登录的错误提示。）
	 * @throws Throwable
	 */
	@Around("webParamPointcut() @annotation(WebParamsRecord))")
	public Object Interceptor(ProceedingJoinPoint joinPoint) throws Throwable {
		/**
		 * gaohj 20190228 参数校验通过执行目标方法
		 */
		Object result = null;// 接口返回值
		try{
			checkWebParams(joinPoint);
		}catch(Exception e){
			logger.info(e.getMessage()+"参数验证不合规");
			return result;
		}
		result = joinPoint.proceed();
		return result;
	}

	/**
	 * author:gaohj 20190228
	 * 
	 * @function:页面参数验证；
	 * @param proceedingJoinPoint @return：参数验证通过true;验证失败false;
	 */
	public void checkWebParams(ProceedingJoinPoint proceedingJoinPoint)throws Exception  {
		logger.info("step into method 参数校验...............");
		try {
			// 获取切面中的参数：待验证key，以及对应的规则
			Signature signature = proceedingJoinPoint.getSignature();// 此处joinPoint的实现类是MethodInvocationProceedingJoinPoint
			MethodSignature methodSignature = (MethodSignature) signature;// 获取参数名
			WebParamsRecord webParamRecord = methodSignature.getMethod().getAnnotation(WebParamsRecord.class);
			logger.info("参数及规则：" + webParamRecord.params());
			// 前端参数
			JSONObject jsonWebParama = JSONObject.parseObject(JSON.toJSONString(proceedingJoinPoint.getArgs()[0]));
			// 获取验证规则
			JSONObject jsonRegulr = JSONObject.parseObject(webParamRecord.params().toString());
			Iterator<String> jsonWebParamaKeys = jsonWebParama.keySet().iterator();

			while (jsonWebParamaKeys.hasNext()) {
				String key = jsonWebParamaKeys.next();
				if (jsonRegulr.containsKey(key)) {
					String regex = jsonRegulr.getString(key);
					String expression = jsonWebParama.getString(key);
					Pattern pattern = Pattern.compile(regex);
					Matcher matcher = pattern.matcher(expression);
					if (!matcher.matches()) {
						throw new Exception(key);
					}
				} 
			}
		}catch(Exception e) {
			logger.error("参数校验失败"+e);
			throw new Exception(e.getMessage());
		}
	}

	public static void main(String args[]) {
		// String regex = "[\\u4e00-\\u9fa5A-Za-z_0-9]{1,64}";//1-64各字符，英文大小写 数字中文以及下划线
		//String regex = "[^\\s]{0,2}";// 0,255个字符
		//String regex = "^0[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]{1}|6553[0-5]|[1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]{1}|6553[0-5]$";//1-65535端口范围
		//String regex="^(?=(\\b|\\D))(((\\d{1,2})|(1\\d{1,2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{1,2})|(2[0-4]\\d)|(25[0-5]))(?=(\\b|\\D))\\/([0-9]|[1-2]\\d|3[0-2])$";//子网段
		String regex="^1(3|4|5|7|8)\\d{9}";
		String expression = "13511111111";
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(expression);
		System.out.println(matcher.matches());
	}

	@Override
	public int getOrder() {
		return 0;
	}
}
